package weaver.batchchanges.servlet;

import weaver.workflow.workflow.WorkflowAllComInfo;
import com.alibaba.fastjson.JSON;
import com.engine.common.util.ParamUtil;
import com.engine.common.util.ServiceUtil;
import com.engine.workflow.biz.requestList.RequestListBiz;
import com.engine.workflow.service.impl.RequestFormServiceImpl;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.batchchanges.bean.BatchTasksChangesRequestData;
import weaver.batchchanges.bean.TaskLedgerPhase2Bean;
import weaver.batchchanges.service.BatchTasksChangesService;
import weaver.batchchanges.service.impl.BatchTasksChangesServiceImpl;
import weaver.batchchanges.wrapper.BatchTasksChangesRequestWrapper;
import weaver.integration.util.JSONUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 批量任务变更接口
 */
@WebServlet("/BatchTasksChanges")
public class BatchTasksChangesServlet extends HttpServlet {
    BaseBean baseBean = new BaseBean();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        this.doGet(req, res);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        this.doPost(req, res);
    }

    private RequestFormServiceImpl getFormService(HttpServletRequest request, HttpServletResponse response) {
//        User user = RequestFormBiz.getFormUser(request, response, false);
        User user = new User(1);
        return (RequestFormServiceImpl) ServiceUtil.getService(RequestFormServiceImpl.class, user);
    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1.获取参数信息
        baseBean.writeLog("---Obtain parameter information start----");
        Map<String, Object> dataArray = ParamUtil.requestJson2Map(request);
        BatchTasksChangesRequestData batchTasksChangesRequestData = BatchTasksChangesRequestData.toClass(dataArray);
        baseBean.writeLog("---Obtain parameter information end----");

        //存放任务变更失败的 任务临时台账表的id
        List<String> failureIds = new ArrayList<>();
        //存放任务变更成功的 任务临时台账表的id
        List<String> successIds = new ArrayList<>();
        //存放任务变更成功，需要更新任务台账二期表的数据
        List<TaskLedgerPhase2Bean> taskLedgerPhase2Beans = new ArrayList<>();

        //2.进行批量任务变更
        baseBean.writeLog("---Batch task changes start----");
        //遍历请求中的 批量任务变更数据，并对每项任务执行任务变更
        batchTasksChangesRequestData.getDataArray().forEach(dataItem -> {
            try {
                BatchTasksChangesRequestWrapper batchTasksChangesRequestWrapper = new BatchTasksChangesRequestWrapper.Builder()
                        .addParameter("requestid", dataItem.getRequestId())
                        .addParameter("requestId", dataItem.getRequestId())
                        .addParameter("workflowid", dataItem.getWorkflowId())
                        .addParameter("nodeid", dataItem.getNodeId())
                        .addParameter("field5", dataItem.getField5())
                        .addParameter("operate", dataItem.getOperate())
                        .addParameter("forwardflag", 3)//转办
                        .addParameter("monitorReqParams", "")
                        .build(request);
                //进行单项任务变更
                Map<String, Object> apidatas = individualTasksChanges(batchTasksChangesRequestWrapper, response);
                if ((Boolean) apidatas.get("success")) {
                    //变更成功后，更新任务台账二期表的数据
                    taskLedgerPhase2Beans.add(new TaskLedgerPhase2Bean() {{
                        setId(dataItem.getOldId());
                        setHdcjr(dataItem.getField5());
                        setBgrwjd(Integer.valueOf(dataItem.getNodeId()));
                    }});
                    successIds.add(String.valueOf(dataItem.getNewId()));
                } else {
                    //变更失败后，保存当前失败的id，
                    failureIds.add(String.valueOf(dataItem.getNewId()));
                }
            } catch (Exception e) {
                baseBean.errorLog("Bulk change errors:::", e);
            }

        });
        baseBean.writeLog("---Batch task changes end----");


        //3.处理批量任务变更后成功和失败的数据
        baseBean.writeLog("---update table data start----");
        try {
            //获取service实例
            BatchTasksChangesService batchTasksChangesService = ServiceUtil.getService(BatchTasksChangesServiceImpl.class);
            //更新批量任务变更成功对应的任务台账二期表数据
            if (!taskLedgerPhase2Beans.isEmpty()) {
                batchTasksChangesService.updateTaskLedgerPhase2(taskLedgerPhase2Beans);
            }
            //更新批量变更失败的临时任务台账表数据状态为失败
            if (!failureIds.isEmpty()) {
                boolean failed = batchTasksChangesService.changeFailed(failureIds);
                baseBean.writeLog("Change the status of the failed setting:::" + failed);
            }
            //删除变更成功任务对应的临时任务台账表数据
            if (!successIds.isEmpty()) {
                boolean b = batchTasksChangesService.deleteBatchTasksChangesTemp(successIds);
                baseBean.writeLog("delete status:::" + b);
            }
        } catch (Exception e) {
            baseBean.errorLog("An exception occurred in the update table data ::: ", e);
        }
        baseBean.writeLog("---update table data end----");


        response.setContentType("text/html;charset=utf-8");
//        response.getWriter().write(JSONUtil.toJSONString(apidatas));
    }


    /**
     * 单项任务变更方法（copy from 单项任务变更接口）
     *
     * @param request
     * @param response
     * @return
     */
    private Map<String, Object> individualTasksChanges(HttpServletRequest request, HttpServletResponse response) {
//        boolean success = true;

        User user = new User(1);
        BaseBean baseBean = new BaseBean();
        Map para2Map = ParamUtil.request2Map(request);
        baseBean.writeLog("para2Map====>" + JSONUtil.toJSONString(para2Map));
        String requestid = (String) para2Map.get("requestid");//当前请求id值
        RecordSet recordSet = new RecordSet();
        String nodeid = (String) para2Map.get("nodeid");//当前节点id
        String workflowid = (String) para2Map.get("workflowid");//workflowid
        String tablename = getTablename(workflowid);
        baseBean.writeLog("tableName===>" + tablename);
        String sql2 = "update " + tablename + " set hdcjr=? where requestid='" + requestid + "'";
        int field5 = Util.getIntValue(request.getParameter("field5"));//新的人
        recordSet.executeUpdate(sql2, field5);
        baseBean.writeLog("sql2===>" + sql2);
        int forwardflag = Util.getIntValue(request.getParameter("forwardflag"));//转办
        String operate = Util.null2String(request.getParameter("operate"), "save");//操作类型，保存日志
        baseBean.writeLog("reququestId==>" + requestid + "====nodeid===>" + nodeid + "===>field5==>" + field5 + "===>operate==>" + operate + "===>workflowid===>" + workflowid);
        //找到流程基础信息表的创建人，对应的操作节点信息的人，修改成新的人
        String sql = "select CREATER from workflow_requestbase where requestid='" + requestid + "'";
        baseBean.writeLog("sql===>" + sql);
        recordSet.execute(sql);
        Map<String, Object> apidatas = getFormService(request, response).forwardSubmit(request);
        baseBean.writeLog("apidatas==>" + JSON.toJSONString(apidatas));
        String openByDefaultBrowser = "".equals(Util.null2String(request.getParameter("openByDefaultBrowser"))) ? "1" : "0";
        baseBean.writeLog("openByDefaultBrowser====>" + openByDefaultBrowser);

        if (forwardflag == 3 && "1".equals(openByDefaultBrowser)) {
            RequestListBiz.putRecord(user, requestid);
        }

        if (recordSet.next()) {
            String creater = recordSet.getString("CREATER");
            baseBean.writeLog("creater===>" + creater);
            //更新节点操作者记录表的当前节点的人为新的人
            String updateSql = "\n" +
                    "update workflow_currentoperator  set userId=" + field5 + "\n" +
                    " where requestid=" + requestid + " and userId=" + creater + "";
            baseBean.writeLog("updateSql==>" + updateSql);
            recordSet.execute(updateSql);

//            String updateSql2="\n" +
//                    "update workflow_currentoperator  set userId="+field5+"\n" +
//                    " where requestid="+requestId+" and nodeid='"+nodeid+"'";
//            baseBean.writeLog("updateSql2==>"+updateSql2);
//            recordSet.execute(updateSql2);
            //更新流程表基本信息的创建者为新的人
            String updateBaseCreateToNewSql = "update workflow_requestbase  set creater=" + field5 + "\n" +
                    " where requestid='" + requestid + "'";
            baseBean.writeLog("updateBaseCreateToNewSql====>" + updateBaseCreateToNewSql);
            recordSet.execute(updateBaseCreateToNewSql);
        }

        response.setContentType("text/html;charset=utf-8");
//        response.getWriter().write(JSONUtil.toJSONString(apidatas));


        return apidatas;
    }

    private String getWorkflowid(String requestid) {
        String workflowid = "";

        RecordSet rs = new RecordSet();
        rs.executeQuery(" select  workflowid from workflow_requestbase  where requestid = " + requestid);
        if (rs.next()) {
            workflowid = rs.getString("workflowid");
        }
        return workflowid;
    }

    private String getTablename(String workflowid) {
        String tablename = "";
        try {
            WorkflowAllComInfo workflowAllComInfo = new WorkflowAllComInfo();
            int formid = com.weaver.general.Util.getIntValue(workflowAllComInfo.getFormId(workflowid), 0);
            int isbill = com.weaver.general.Util.getIntValue(workflowAllComInfo.getIsBill(workflowid));
            if (formid == 0) {
                String sql = "select formid,isbill from workflow_base where id = " + workflowid;
                RecordSet rs = new RecordSet();
                rs.execute(sql);
                if (rs.next()) {
                    formid = rs.getInt("formid");
                    isbill = rs.getInt("isbill");
                }
            }
            tablename = getTablename(formid, isbill);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tablename;
    }

    /**
     * 获取流程主表名称
     *
     * @param formid
     * @param isbill
     * @return
     */
    private String getTablename(int formid, int isbill) {
        RecordSet rs = new RecordSet();
        String billtablename = "";
        if (isbill == 1) {
            rs.executeQuery("select tablename from workflow_bill where id =? ", formid); // 查询工作流单据表的信息
            if (rs.next())
                billtablename = rs.getString("tablename");          // 获得单据的主表
        } else {
            billtablename = "workflow_form";
        }
        return billtablename;
    }
}
